import wxRquest from 'mina-request'
import {
  getStorage,
  clearStorage
} from './store'
import {
  toast,
  model,
} from './extendAPI'

// 实例
const instance = new wxRquest({
  baseURL: 'https://gmall-prod.atguigu.cn/mall-api',
  timeout: 10000,
})
// 拦截请求
instance.interceptors.request = (config) => {
  // 请求前携带token
  const token = getStorage('token')
  if (token) {
    config.header['token'] = token
  }
  return config
}
instance.interceptors.response = async (res) => {
  if (!res.isSuccess) {
    toast({
      title: '网络异常',
      icon: 'error'
    })
    return Promise.reject(res.errMsg)
  }
  switch (res.data.code) {
    case 200:
      return Promise.resolve(res.data)
    case 208:
      const result = await model({
        content: "鉴权失败,请重新登录",
        showCancel: false
      })
      // 点击确定.清除信息
      if (result) {
        clearStorage()
        wx.navigateTo({
          url: '/pages/login/login',
        })
      }
      return Promise.reject(res)

    default:
      toast({
        title: "异常,稍后重试"
      })
      return Promise.reject(res)
  }

}

export default instance